<?php
namespace app\crm\model;
use think\Model;
use think\Db;
use think\Cache;
use think\Loader;

/*
快递100接口推送
*/
class Expressdelivery extends Model
{
	//改变订单信息
	public function updateOrderInfo($logistics_account,$state,$info){
		if(!$logistics_account){
			$logistics_account = $_REQUEST["logistics_account"];
		}
		if(!isset($state)){
			$state = $_REQUEST["state"];
		}
		// print_r($state);exit;
		if(!$info){
			$info = json_decode($_REQUEST["info"],true);
		}
		
		$receipttime = substr($info,0,19);
		
		// $order_info = M("order_info");
		// $arrF = Db::name('order_info')->field("id,order_num,createname,logistics_account,cope_money,stored_values,customer_id,shopping_name,sign_back_number")->where("logistics_account = '$logistics_account'")->find();
		// echo $order_info->getLastSql();exit;
		//推送坐席
		// $row_logistics_state = array("0"=>"在途","1"=>"揽件","2"=>"疑难","3"=>"签收","4"=>"退签","5"=>"派件","6"=>"退回","7"=>"转投");
		// $arrPustData = array(
		// 	"type"=>"order",
		// 	"order_num"=>$arrF["order_num"],
		// 	"push_msg"=>$row_logistics_state[$state],
		// 	"content"=>"您订单号为：".$arrF["order_num"]." 物流状态：".$row_logistics_state[$state]
		// );
		// $arrTRy[0] = $arrPustData;
		//echo "http://localhost/msgInterface/pub?user=U".$arrF["createname"].json_encode($arrTRy);die;
		
		// $customer = M(customer);
		// $customer_id = $arrF["customer_id"];
		$arrD = array(
			"logistics_state"=>$state,
			"logistics_Info"=>$info,
			// "view_enable"=>"N",  //订单状态更变提醒
			// "logistics_time2"=>date("Y-m-d H:i:s"),  //物流更新时间
			"logistics_time"=>$receipttime,  //快递100推送过来的时间
		);
		if($state == "3"){
			$arrD["order_status"] = "1";  //已确认
			$arrD["shipping_status"] = "2";  //收货确认
			//$arrD["receipttime"] = date("Y-m-d H:i:s");   //签收时间
			$arrD["receipttime"] = $receipttime;   //签收时间
			
			//付款
			$arrD["pay_status"] = "Y";  
			$arrD["payment"] = "3";     //付款方式--货到付款
			$arrD["paytime"] = date("Y-m-d H:i:s");
			
			/*//当签收的时候，将预存减去这个订单的预存，如减去后还有预存，则将预存是否冻结的状态改成否
			$arrC = $customer->field("id,stored_value,stored_frozen")->find();
			$stored_value = $arrC["stored_value"]-$arrF["stored_values"];
			if($stored_value > 0){
				$stored_frozen = "N";   //不冻结
			}else{
				$stored_frozen = "Y";   //冻结
			}
			$arrCD = array(
				"stored_value"=>$stored_value,
				"stored_frozen"=>$stored_frozen
			);
			
			$res = $customer->data($arrCD)->where("id = '$customer_id'")->save();*/
			//return $customer->getLastSql();die;
		}elseif($state == "4"){
			//state == "4":货物退回发货人并签收  state == "6":货物正处于返回发货人的途中
			$arrD["order_status"] = "4";  //退货
			$arrD["pay_status"] = "N";  //未付款
			$arrD["shipping_status"] = "0";  //未发货
			//$arrD["canceltime"] = date("Y-m-d H:i:s"); //退货时间
			$arrD["canceltime"] = $receipttime; //退货时间
			/*$arrD["description4"] = "快递100接口推送改变状态";  //操作备注
			$arrD["refund4"] = "";  //退款方式
			$arrD["explanation4"] = "快递100接口推送改变状态";  //退款说明
			
			$arrD["sign_back_number"] = $arrF["sign_back_number"]+1;  //退签次数
			
			
			//第一次退签
			if($arrF["sign_back_number"] == '0'){
				//当拒收是，积分减去这个订单的积分，
				$arrC = $customer->field("id,stored_value,stored_frozen,integral")->find();
				$integral = $arrC["integral"]-$arrF["cope_money"];
				$arrCD = array(
					"integral"=>$integral
				);
				$res = $customer->data($arrCD)->where("id = '$customer_id'")->save();
				
				//退签的要重新订阅一次
				$express_id = $arrF["shopping_name"];
				$this->pushExpress($logistics_account,$express_id);
			}*/
		}else{
		
		}
		
		$result = Db::name('order_info')->where("logistics_account = '$logistics_account'")->update($arrD);
		//echo $order_info->getLastSql();die;
		if ($result !== false){
			// if($state == "3" || $state == "4"){
			// 	//积分--如果有快递100推送的就改成在签收之后，否者就确定订单之后
			// 	$this->saveIntegral($customer_id);
			// }
			// $this->phpPush(json_encode($arrTRy),$arrF["createname"]);
			if($_REQUEST["logistics_account"]){
				echo "true";
			}else{
				return true;
			}
			
		} else {
			if($_REQUEST["logistics_account"]){
				echo "false";
			}else{
				return false;
			}
		}
		
	}
	
	//用户积分
	public function saveIntegral($customer_id){
		//$customer_id = "48";
		$order_info = new Model("order_info");
		$arrF = $order_info->field("sum(goods_amount) as goods_amount,id")->where("customer_id = '$customer_id' AND logistics_state = '3'")->find();
		$integral = $arrF["goods_amount"];
		if(!$integral || $integral == "0.00"){
			$integral = "0";
		}
		//echo $order_info->getLastSql();
		
		$membership_level = M("membership_level");
		$arrML = $membership_level->where(" start_num <= '$integral' AND end_num >= '$integral'")->find();
		$groups = $arrML["groups"];
		if(!$arrML){
			if(!$integral){
				$groups = "failure";
			}else{
				$arrML2 = $membership_level->where("end_num = '0'")->find();
				$groups = $arrML2["groups"];
			}
		}
		
		$customer = M("customer");
		$arrData = array(
			"integral"=>$integral,
			"member_Level"=>$groups,
		);
		$res = $customer->data($arrData)->where("id = '$customer_id'")->save();
		return true;
	}

	
	public function saveRealtimeExpress(){
		$username = $_SESSION['user_info']['username'];
		$d_id = $_SESSION['user_info']['d_id'];
		$para_sys = Cache::get('system');
		// $order_info = M("order_info");
		$id = $_REQUEST["id"];
		$start_time = $_REQUEST["start_time"];
		$end_time = $_REQUEST["end_time"];
		$user_name = $_REQUEST["user_name"];
		$dept_id = $_REQUEST["dept_id"];

		$arrDep = $this->getDepTreeData();
		$deptst = $this->getMeAndSubDeptID($arrDep,$dept_id);  //取上级部门
		$deptSet = rtrim($deptst,",");
		
		$deptst2 = $this->getMeAndSubDeptID($arrDep,$d_id);  //取上级部门
		$deptSet2 = rtrim($deptst2,",");

		if(!$dept_id){
			$deptId = $deptSet2;
		}else{
			$deptId = $deptSet;
		}
		
		$where = "1 ";
		$where .= " AND logistics_account!='' AND logistics_account is not null ";
		$where .= empty($id) ? "" : " AND id in ($id)";
		$where .= empty($start_time) ? "" : " AND createtime >= '$start_time'";
		$where .= empty($end_time) ? "" : " AND createtime <= '$end_time'";
		$where .= empty($user_name) ? "" : " AND createname = '$user_name'";
		
		$menuname = "Order List";
		$p_menuname = $_SESSION['menu'][$menuname]; //父菜单
		$priv = $_SESSION["user_priv"][$p_menuname][$menuname];		
		if($username != "admin" || $dept_id){
			if( $priv["all"] != "Y"  || $dept_id){
				$where .= " AND dept_id in ($deptId)";
			}
		}
		
		$arrData = Db::name('order_info')->field("id,shopping_name,logistics_account")->where($where)->select();
		//echo $order_info->getLastSql();
		//dump($where);die; 
		
		$success = $failure = 0;
		foreach($arrData as $val){
			if($val["logistics_account"]){
				//$url = "http://".$para_sys["intranet_ip"]."/index.php?m=ExpressDelivery&a=realtimeExpress";
				// $url = "http://192.168.88.59/index.php/crm/Expressdelivery/realtimeExpress";
				$param = array(
					"logistics_account"=>$val["logistics_account"],
					"express_id"=>$val["shopping_name"],
					"company"=>"AJ"
				);
				// print_r($param);exit();
				// $rseult = getHttpPost($url,$param);
				$rseult = $this->realtimeExpress($param['logistics_account'],$param['express_id']);
				// print_r($url);die;
				//dump($param);die; 
				//dump(json_decode($rseult,true));die;
				if($rseult == "true"){
					sleep(1);
					$rseult = true;
				}else{
					$rseult = false;
				}
				//dump($rseult);die;
				//$rseult = $this->realtimeExpress($val["logistics_account"],$val["shopping_name"]);
			}else{
				$rseult = false;
			}
			if($rseult){
				$success++;
			}else{
				$failure++;
			}
		}
		if($success == "0"){
			$msg = "手动查询物流信息失败,原因：查询无结果，请隔段时间再查";
		}else{
			$msg = "手动查询物流信息成功 $success 条，失败： $failure 条";
		}
		echo json_encode(array('success'=>true,'msg'=>$msg));
		//dump($arrF);die;
	}
	
	public function realtimeExpress($logistics_account,$express_id){
		// print_r($_REQUEST);exit;
		if(!$logistics_account){
			$logistics_account = $_REQUEST["logistics_account"];
		}		
		if(!$express_id){
			$express_id = $_REQUEST["express_id"];
		}
		
		$para_sys = Cache::get('system');
		
		// $logistics_mode = M("order_logistics_mode");
		$arrM = Db::name('order_logistics_mode')->select();
		foreach($arrM as $val){
			$row_shopping_name[$val["id"]] = $val["com_code"];
		}
		
		//你那边如果不确定出发地，目的地可以不填写，一旦填写了解析系统会以你填写的权重会很高"from":"广东深圳", "to":"北京丰台"
		$company_name = $row_shopping_name[$express_id];
		
		//参数设置
		$post_data = array();
		$post_data["customer"] = $para_sys["express_customer"];
		$key= $para_sys["express_key"];
		$post_data["param"] = '{"com":"'.$company_name.'","num":"'.$logistics_account.'"}';

		$url='http://www.kuaidi100.com/poll/query.do';
		$post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
		$post_data["sign"] = strtoupper($post_data["sign"]);
		$o=""; 
		foreach ($post_data as $k=>$v)
		{
			$o.= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
		}
		$post_data=substr($o,0,-1);
		// print_r($post_data);exit;
		/*
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		$result = curl_exec($ch);
		curl_close($ch);
		$data = str_replace("\&quot;",'"',$result );
		$arrData = json_decode($data,true);
		*/
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);
		curl_close($ch);
		$data = str_replace("\&quot;",'"',$result );
		$arrData = json_decode($data,true);
		//dump($arrData);die;
		// print_r($arrData);die;
		
		
		$logisticsAccount = $arrData["nu"]; // 物流号
		$state = $arrData["state"]; // 物流状态
		// print_r($state);exit;
		$arrInfo = $arrData["data"];
		foreach($arrInfo as $val){
			$arrF[] = $val["time"]." &nbsp;&nbsp;|&nbsp;&nbsp;".$val["context"];
		}
		$info = implode("<br>",$arrF); // 物流信息
		// print_r($info);exit;
		if($info){
			$result = $this->updateOrderInfo($logisticsAccount,$state,$info);
			// print_r($result);exit;
			// echo $result;die;
			if ($result !== false){
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
		sleep(1);
	}
	


	/*
	* 获得一个数组，该数组是一维数组，存放id，名称，id和下一级别部门的id
	*/
	function getDepTreeData(){
		$DepTree = array();//一维数组
		$arr = Db::name('sys_department')->select();
		foreach($arr AS $v){
			$currentId = $v['department_id'];
			$arrSonId = Db::name('sys_department')->field('department_id')->where("department_pid=$currentId")->select();
			$strId = "$currentId";
			foreach($arrSonId AS $row){
				$strId .= "," . $row['department_id'];
			}
			$arrDepTree[$currentId] = Array(
				"id" => $v['department_id'],
				"pid" => $v['department_pid'],
				"name"=> $v['department_name'],
				"meAndSonId"=>$strId,
			);
		}
		//dump($arrDepTree);die;
		return $arrDepTree;
	}

	function getMeAndSubDeptID($arrDep,$dept_id){
		$arrId = explode(',',$arrDep[$dept_id]['meAndSonId']);
		//$str = "'" . $arrDep[$dept_id]['name'] . "',";
		$str = "'" . $arrDep[$dept_id]['id'] . "',";
		if( array_shift($arrId) ){
			foreach( $arrId AS $id ){
				$str .= $this->getMeAndSubDeptID($arrDep,$id);
			}
		}
		return $str;
		
	}
}

?>